package com.sinszm.sofa.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.lang.reflect.Field;
import java.util.stream.Collectors;

/**
 * 分页数据格式化工具
 *
 * @author admin
 * @date 2021/10/12
 */
public class PageFormatUtil {

    /**
     * 计算指数
     *
     * @param response 响应
     * @param index    指数
     * @return long
     */
    private static <T> long calculateIndex(Page<T> response, Integer index) {
        int currentIndex = (index == null ? 0 : index) + 1;
        return response.getCurrent() <= 1 ? currentIndex : currentIndex + (response.getCurrent() - 1) * response.getSize();
    }

    /**
     * 格式
     *
     * @param list           列表
     * @param clazz          clazz
     * @param indexFieldName 序号字段名
     * @return {@link Page<T>}
     */
    public static <E,T> Page<T> format(Page<E> list, Class<T> clazz, String indexFieldName) {
        Page<T> result = new Page<>(list.getCurrent(), list.getSize(), list.getTotal(),list.isSearchCount());
        result.setOrders(list.getOrders());
        result.setHitCount(list.isHitCount());
        result.setOptimizeCountSql(list.isOptimizeCountSql());
        result.setRecords(
                list.getRecords().stream()
                        .map(l -> {
                            T r = ReflectUtil.newInstance(clazz);
                            BeanUtil.copyProperties(l, r);
                            return r;
                        })
                        .peek(BaseUtil.consumerWithIndex((data, index) -> {
                            Field field = ReflectUtil.getField(clazz, indexFieldName);
                            if (field != null) {
                                field.setAccessible(true);
                                ReflectUtil.setFieldValue(data, field, calculateIndex(result, index));
                            }
                        }))
                        .collect(Collectors.toList())
        );
        return result;
    }

}
